﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;

using Autofac;

using octalforty.Componento.Commands;
using octalforty.Componento.Core.ApplicationServices;

using System.Linq;

using octalforty.Componento.Core.Framework;

namespace octalforty.Componento
{
    class Program
    {
        static void Main(string[] args)
        {
            var containerBuilder = new ContainerBuilder();
            containerBuilder.RegisterType<MetadirectoryManagerService>().AsSelf().AsImplementedInterfaces().PropertiesAutowired();
            containerBuilder.RegisterType<PackageRepositoryBrowserService>().AsSelf().AsImplementedInterfaces().PropertiesAutowired();
            containerBuilder.RegisterType<DependencyGraphManagerService>().AsSelf().AsImplementedInterfaces().PropertiesAutowired();
            containerBuilder.RegisterType<PackageResourceProviderService>().AsSelf().AsImplementedInterfaces().PropertiesAutowired();
            containerBuilder.RegisterType<PackageInstallerService>().AsSelf().AsImplementedInterfaces().PropertiesAutowired();
            containerBuilder.RegisterType<PackageResourceInstallerService>().AsSelf().AsImplementedInterfaces().PropertiesAutowired();

            containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(t => typeof(ICommand).IsAssignableFrom(t) && !t.IsAbstract).AsSelf().AsImplementedInterfaces().PropertiesAutowired();
            containerBuilder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).Where(t => typeof(IPackageRepositoryBrowser).IsAssignableFrom(t) && !t.IsAbstract).AsSelf().AsImplementedInterfaces().PropertiesAutowired();

            //Trace.Listeners.Add(new ConsoleTraceListener() { TraceOutputOptions = TraceOptions.Timestamp});
            containerBuilder.RegisterInstance(new TraceSource("Componento", SourceLevels.All));
            var container = containerBuilder.Build();

            var commandName = args.Length == 0 ? "help" : args[0].ToLowerInvariant();
            var commands =
                from c in container.Resolve<IEnumerable<ICommand>>()
                let a = ((CommandAttribute)c.GetType().GetCustomAttributes(typeof(CommandAttribute), false)[0])
                where a.Name.ToLowerInvariant() == commandName || (!string.IsNullOrEmpty(a.Aliases) && a.Aliases.ToLowerInvariant().Split(';').Contains(commandName))
                select c;

            var command = commands.Single();

            Console.WriteLine("octalforty Componento - (c) 2010 octalforty studios");
            Console.WriteLine();

            command.Execute(args.Skip(1).ToArray());
        }
    }
}
